<?php
namespace app\entries\controller;
use think\Controller;
use think\Loader;
use think\Db;

/**
 *
 */
class Jren extends Logincheck
{

    //查看匠人信息页面
    function jiangren()
    {
        //返回茶类
        $retval = getTeaCase();
        $this->assign('teacase', $retval);

        //返回产区
        $retval = getTeaArea();
        $this->assign('teaarea', $retval);

        return $this->fetch();
    }


    //获取对应参数的匠人信息
    function getChoose($teacase, $teaarea)
    {
        $this->assign('choosetea', $teacase);
        $this->assign('choosearea', $teaarea);
        //查询匠人榜单信息
        if($teacase == 10000){
            return $this->redirect('getAll');
        }else if($teacase == 9999){
            return $this->redirect('getOther');
        }else{
            if($teaarea==10000){
                //取某茶类全部
                $data = ['teacase_id'=>$teacase];
                $retval = getChoose("jiangren", $data);//参数1为表单名称，$data为查询条件
                $rank = 1;
                $tid_name = teacase_ids();
                $aid_name = teaarea_ids();
                foreach ($retval as &$r) {
                    $r['rank'] = $rank;
                    $rank++;
                    $r['teacase'] = $tid_name[$r['teacase_id']];
                    $r['teaarea'] = $aid_name[$r['teaarea_id']];
                    $areas = db("case_area")->field('teaarea_id')->where("teacase_id",$r['teacase_id'])->select();
                    foreach ($areas as &$a) {
                        $a['area'] = $aid_name[$a['teaarea_id']];
                    }
                    $r['areas'] = $areas;
                }
            }else if($teaarea==9999){
                //取未上榜
                $data = ['teacase_id'=>$teacase, 'bangdan_id'=>4];
                $retval = getChoose("jiangren", $data);//参数1为表单名称，$data为查询条件
                $rank = 1;
                $tid_name = teacase_ids();
                $aid_name = teaarea_ids();
                foreach ($retval as &$r) {
                    $r['rank'] = $rank;
                    $rank++;
                    $r['teacase'] = $tid_name[$r['teacase_id']];
                    $r['teaarea'] = $aid_name[$r['teaarea_id']];
                    $areas = db("case_area")->field('teaarea_id')->where("teacase_id",$r['teacase_id'])->select();
                    foreach ($areas as &$a) {
                        $a['area'] = $aid_name[$a['teaarea_id']];
                    }
                    $r['areas'] = $areas;
                }
            }else{
                //取某茶类某产区
                $data = [
                    'teacase_id'=>$teacase,
                    'teaarea_id'=> $teaarea
                ];
                $retval = getChoose("jiangren", $data);//参数1为表单名称，$data为查询条件
                $rank = 1;
                $tid_name = teacase_ids();
                $aid_name = teaarea_ids();
                foreach ($retval as &$r) {
                    $r['rank'] = $rank;
                    $rank++;
                    $r['teacase'] = $tid_name[$r['teacase_id']];
                    $r['teaarea'] = $aid_name[$r['teaarea_id']];
                    $areas = db("case_area")->field('teaarea_id')->where("teacase_id",$r['teacase_id'])->select();
                    foreach ($areas as &$a) {
                        $a['area'] = $aid_name[$a['teaarea_id']];
                    }
                    $r['areas'] = $areas;
                }
            }
        }
        $this->assign('data', $retval);

        //获取当前茶类的名称
        $retval = getTeaCaseName($teacase);
        $this->assign('current', $retval);
        //获取当前产区的名称
        $retval = getTeaAreaName($teaarea);
        $this->assign('currentArea', $retval);
        //获取所有茶类
        $retval = getTeaCase();
        $this->assign('teacase', $retval);

        //获取产区
        $retval = $this->reTeaArea($teacase);
        $this->assign('teaarea', $retval);

        $this->assign('choosetea', $teacase);
        $this->assign('choosearea', $teaarea);

        return $this->fetch('get_all');
    }

    //显示所有匠人
    function getAll()
    {
        $tid_name = teacase_ids();
        $aid_name = teaarea_ids();
        $rank = 1;
        $retval =  model('Jren')->getAlljr();
        foreach ($retval as &$r) {
            $r['rank'] = $rank;
            $rank++;
            $r['teacase'] = $tid_name[$r['teacase_id']];
            $r['teaarea'] = $aid_name[$r['teaarea_id']];
            $areas = db("case_area")->field('teaarea_id')->where("teacase_id",$r['teacase_id'])->select();
            foreach ($areas as &$a) {
                $a['area'] = $aid_name[$a['teaarea_id']];
            }
            $r['areas'] = $areas;
        }
        $this->assign('data', $retval);
        //获取茶类
        $retval = getTeaCase();
        $this->assign('teacase', $retval);
        $this->assign('choosetea', 10000);
        $this->assign('choosearea', 10000);
        //获取茶类的名称
        $this->assign('current', '');
        //获取产区的名称
        $this->assign('currentArea', '');
        return $this->fetch();
    }

    //显示未上榜匠人
    function getOther()
    {
        $tid_name = teacase_ids();
        $aid_name = teaarea_ids();
        $rank = 1;
        $retval =  model('Jren')->getOther();

        foreach ($retval as &$r) {
            $r['rank'] = $rank;
            $rank++;
            $r['teacase'] = $tid_name[$r['teacase_id']];
            $r['teaarea'] = $aid_name[$r['teaarea_id']];
            $areas = db("case_area")->field('teaarea_id')->where("teacase_id",$r['teacase_id'])->select();
            foreach ($areas as &$a) {
                $a['area'] = $aid_name[$a['teaarea_id']];
            }
            $r['areas'] = $areas;
        }
        $this->assign('data', $retval);
        //获取茶类
        $retval = getTeaCase();
        $this->assign('teacase', $retval);
        $this->assign('choosetea', 9999);
        $this->assign('choosearea', 9999);
        //获取茶类的名称
        $this->assign('current', '');
        //获取产区的名称
        $this->assign('currentArea', '');
        return $this->fetch('get_all');
    }

    //修改匠人信息
    function modifyJren($id, $teacase, $teaarea, $name, $score, $contact, $phone, $wechat, $briefintro, $detailintro)
    {
        $tid = ids_teacase();
        $aid = ids_teaarea();
        $data = [
            // "teacase_id"=>$tid[$teacase],
            "teacase_id"=>$teacase,
            "teaarea_id"=>$aid[$teaarea],
            "name"=>$name,
            "score"=>$score,
            "briefintro"=>$briefintro,
            "contact"=>$contact,
            "phone"=>$phone,
            "wechat"=>$wechat,
            "detailintro"=>$detailintro,
            "updatetime"=>time()
        ];
        $retval = model('Jren')->modifyJren($id, $data);
        return $retval;
    }

    //是否上榜
    function shangbang($id, $bangdan_id)
    {
        $data = ['bangdan_id'=>$bangdan_id];
        $retval = model('Jren')->modifyJren($id, $data);
        return $retval;
    }

    //显示手动添加匠人信息页面
    function addjiangren()
    {
        //获得茶类
        $retval = getTeaCase();
        $this->assign("teacase", $retval);
        //获得榜单
        $retval = getBangDan();
        $this->assign("bangdan", $retval);

        return $this->fetch();
    }

    //增加匠人信息
    function addjr($name, $score, $teacase, $teaarea, $bangdan, $briefintro, $contact, $phone, $wechat, $detailintro)
    {
        //工作年限得分
        $seniority = $this->seniority($detailintro);

        //荣誉得分
        $honor_point = $this->honorPoint($briefintro);
        if($honor_point==0){
            $honor_point = $this->honorPoint($detailintro);
        }

        //社会认可度得分
        $recognition_point = $this->recognition($briefintro);
        if($recognition_point==0){
            $recognition_point = $this->recognition($detailintro);
        }

        //社会身份得分
        $socialIdentity = $this->socialIdentity($briefintro);
        if($socialIdentity ==0){
            $socialIdentity = $this->socialIdentity($detailintro);
        }

        $random = rand(0,30)*10;
        $score = $score + $seniority + $honor_point + $recognition_point + $socialIdentity  + $random;

        $data = [
            "name" => $name,
            "score" => $score,
            "teacase_id" => $teacase,
            "teaarea_id" => $teaarea,
            "bangdan_id" => $bangdan,
            "briefintro" => $briefintro,
            "contact" => $contact,
            "phone" => $phone,
            "wechat" => $wechat,
            "detailintro" => $detailintro,
            "addtime" => time()
        ];
        $retval = model('Jren')->addjr($data);
        if($retval == 1){
            return $this->success("添加成功");
        }else{
            return $this->error("添加失败");
        }
    }

    //删除匠人信息
    function delJr($id)
    {
        $retval = model("Jren")->delJr($id);
        if($retval != 1){
            return 0;
        }else{
            return 1;
        }
    }

    //从Excel导入匠人页面
    function fromExceljr()
    {
        return $this->fetch();
    }


    //从excel导入数据
    function inserExcel()
    {
        if(request() -> isPost())
        {
            Loader::import('PHPExcel.Classes.PHPExcel');
            Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
            Loader::import('PHPExcel.Classes.PHPExcel.Reader.Excel5');
            //获取表单上传文件
            $file = request()->file('excel');
            $info = $file->validate(['ext' => 'xlsx'])->move(ROOT_PATH . 'public');  //上传验证后缀名,以及上传之后移动的地址  \public 目录下

            if($info)
            {
                //echo $info->getFilename();
                $exclePath = $info->getSaveName();  //获取文件名
                $file_name = ROOT_PATH . 'public' . DS . $exclePath;//上传文件的地址
                $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
                $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8

                $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
                array_shift($excel_array);  //删除第一个数组(标题);

                $data = [];
                foreach($excel_array as $k=>$v) {

                    //工作年限得分
                    $seniority = $this->seniority($v[10]);

                    //荣誉得分
                    $honor_point = $this->honorPoint($v[6]);
                    if($honor_point==0){
                        $honor_point = $this->honorPoint($v[10]);
                    }

                    //社会认可度得分
                    $recognition_point = $this->recognition($v[6]);
                    if($recognition_point==0){
                        $recognition_point = $this->recognition($v[10]);
                    }

                    //社会身份得分
                    $socialIdentity = $this->socialIdentity($v[6]);
                    if($socialIdentity ==0){
                        $socialIdentity = $this->socialIdentity($v[10]);
                    }

                    $random = rand(0,30)*10;
                    $score = $v[5] + $seniority + $honor_point + $recognition_point + $socialIdentity + $random;

                    $data[$k]['teacase'] = $v[1];
                    $data[$k]['teaarea'] = $v[2];
                    $data[$k]['bangdan'] = $v[3];
                    $data[$k]['name'] = $v[4];
                    // $data[$k]['score'] = $v[5];
                    $data[$k]['score'] = $score;
                    $data[$k]['briefintro'] = $v[6];
                    $data[$k]['contact'] = $v[7];
                    $data[$k]['phone'] = $v[8];
                    $data[$k]['wechat'] = $v[9];
                    $data[$k]['detailintro'] = $v[10];
                 }
                 $retval = model("Jren")->insertExcel($data);
                 if($retval==1){
                    return $this->success("上传数据成功");
                 }else{
                    return $this->error("上传数据出错");
                 }

            }else
            {
                echo $file->getError();
            }
        }else
        {
            return $this -> fetch();
        }
    }

    //数据导出到Excel
    function exportExcel($teacase, $teaarea)
    {
        $name = date('Y-m-d H-i-s').'.'.'xlsx';
        $path = dirname(__FILE__); //找到当前脚本所在路径
        Loader::import('PHPExcel.Classes.PHPExcel');//手动引入PHPExcel.php
        Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');//引入IOFactory.php文件里面的PHPExcel_IOFactory这个类
        $PHPExcel = new \PHPExcel();//实例化
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle("匠人"); //给当前活动sheet设置名称
        //设置表头
        $PHPSheet->setCellValue("A1","序号");//表格数据
        $PHPSheet->setCellValue("B1","茶类");
        $PHPSheet->setCellValue("C1","区域");
        $PHPSheet->setCellValue("D1","榜单");
        $PHPSheet->setCellValue("E1","姓名");
        $PHPSheet->setCellValue("F1","匠心指数（请填写0~100之间的数字）");
        $PHPSheet->setCellValue("G1","称号及成就（30字以内）");
        $PHPSheet->setCellValue("H1","联系人");
        $PHPSheet->setCellValue("I1","电话");
        $PHPSheet->setCellValue("J1","微信");
        $PHPSheet->setCellValue("K1","详细介绍（300~500字）");

        // $teacase, $teaarea
        $tid_name = teacase_ids();
        $aid_name = teaarea_ids();
        $rank = 1;
        if($teacase == 10000){
            $retval =  model('Jren')->getAlljr();
            foreach ($retval as &$r) {
                $r['rank'] = $rank;
                $rank++;
                $r['teacase'] = $tid_name[$r['teacase_id']];
                $r['teaarea'] = $aid_name[$r['teaarea_id']];
            }
        }else if($teacase == 9999){
            $retval =  model('Jren')->getOther();
            foreach ($retval as &$r) {
                $r['rank'] = $rank;
                $rank++;
                $r['teacase'] = $tid_name[$r['teacase_id']];
                $r['teaarea'] = $aid_name[$r['teaarea_id']];
            }
        }else{
            if($teaarea==10000){
                //取某茶类全部
                $data = ['teacase_id'=>$teacase];
                $retval = getChoose("jiangren", $data);//参数1为表单名称，$data为查询条件
                foreach ($retval as &$r) {
                    $r['rank'] = $rank;
                    $rank++;
                    $r['teacase'] = $tid_name[$r['teacase_id']];
                    $r['teaarea'] = $aid_name[$r['teaarea_id']];
                }
            }else if($teaarea==9999){
                //取未上榜
                $data = ['bangdan_id'=>4];
                $retval = getChoose("jiangren", $data);//参数1为表单名称，$data为查询条件
                foreach ($retval as &$r) {
                    $r['rank'] = $rank;
                    $rank++;
                    $r['teacase'] = $tid_name[$r['teacase_id']];
                    $r['teaarea'] = $aid_name[$r['teaarea_id']];
                }
            }else{
                //取某茶类某产区
                $data = [
                    'teacase_id'=>$teacase,
                    'teaarea_id'=> $teaarea
                ];
                $retval = getChoose("jiangren", $data);//参数1为表单名称，$data为查询条件
                foreach ($retval as &$r) {
                    $r['rank'] = $rank;
                    $rank++;
                    $r['teacase'] = $tid_name[$r['teacase_id']];
                    $r['teaarea'] = $aid_name[$r['teaarea_id']];
                }
            }
        }

        $i=2;
        foreach ($retval as $ret) {
            $PHPSheet->setCellValue("A".$i,$ret['id']);//表格数据
            $PHPSheet->setCellValue("B".$i,$ret['teacase']);
            $PHPSheet->setCellValue("C".$i,$ret['teaarea']);
            $PHPSheet->setCellValue("D".$i,"匠人百科");
            $PHPSheet->setCellValue("E".$i,$ret['name']);
            $PHPSheet->setCellValue("F".$i,$ret['score']);
            $PHPSheet->setCellValue("G".$i,$ret['briefintro']);
            $PHPSheet->setCellValue("H".$i,$ret['contact']);
            $PHPSheet->setCellValue("I".$i,$ret['phone']);
            $PHPSheet->setCellValue("J".$i,$ret['wechat']);
            $PHPSheet->setCellValue("K".$i,$ret['detailintro']);
            $i++;
        }

        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");//创建生成的格式
        header("Content-Disposition: attachment;filename=$name");//下载下来的表格名
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }


    //返回某茶类对应的产地JSON数据
    function reTeaAreaJson($teacase_id)
    {
        // $data = $this->reTeaArea($teacase_id);
        $data = $this->reTeaArea($teacase_id);
        return json_encode($data);
    }


    //返回某茶类对应的产地
    function reTeaArea($teacase_id)
    {
        $retval = model("Jren")->reTeaArea($teacase_id);
        $areas = getTeaArea();
        $data = [];
        foreach ($retval as $ret) {
            foreach ($areas as $area) {
                if($ret["teaarea_id"]==$area["id"]){
                    $data[] = $area;
               }
           }
       }
       return $data;
    }



/***************************************************************/
    //计算工作年限
    function seniority($string)
    {
        // $pattern = '/出生于(\d{4})/';
        $pattern = '/(\d{4})/';
        preg_match_all($pattern, $string, $born);
        if(!$born[1]){
            return 0;
        }
        $now = date("Y");
        $cyear = $now - $born[1][0];
        if($cyear<0){
            $cyear = 0;
        }
        $point = Ingenuity_year_calculation($cyear);
        return $point;
    }


    //计算荣誉得分
    function honorPoint($string)
    {
        //国家部委2000 省厅级1000 市局级500 县局级300 封顶3000
        $point = 0;
        $string = $string;

        $pattern = "/国家.{0,22}委/";//一个中文算三个字符，22可以匹配七个字符
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point1 = 2000;
            $point += $point1;
            // echo "国委:".$point1."<br>";
        }

        $pattern = "/省.{0,22}委/";
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point2 = 1000;
            $point += $point2;
            // echo "省委:".$point2."<br>";
        }

        $pattern = "/市.{0,22}委/";
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point3 = 500;
            $point += $point3;
            // echo "市委:".$point3."<br>";
        }

        $pattern = "/县.{0,22}委/";
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point4 = 300;
            $point += $point4;
            // echo "县委:".$point4."<br>";
        }

        if($point > 3000){
            $point = 3000;
        }
        return $point;
    }

    //社会认可度
    function recognition($string)
    {
        //高级1500 副高级1000 中级750
        $point = 0;
        $string = $string;

        $pattern = "/中级/";
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point1 = 750;
            $point += $point1;
        }

        $pattern = "/副高级/";
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point2 = 1000;
            $point += $point2;
        }else{
            $pattern = "/高级/";
            $reg = $this->reg($pattern, $string);
            if($reg){
                $point3 = 1500;
                $point += $point3;
            }
        }

        $pattern = "/评茶/";
        $reg1 = $this->reg($pattern, $string);
        $pattern = "/加工/";
        $reg2 = $this->reg($pattern, $string);
        $pattern = "/制茶/";
        $reg3 = $this->reg($pattern, $string);
        if($reg1 || $reg2 || $reg3){
            $point4 = 750;
            $point += $point4;
        }

        $pattern = "/大师/";
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point5 = 1000;
            $point += $point5;
        }

        $pattern = "/王/";
        $reg = $this->reg($pattern, $string);
        if($reg){
            $point6 = 1000;
            $point += $point6;
        }

        if($point > 1500){
            $point = 1500;
        }
        return $point;
    }

    // 社会身份
    function socialIdentity($string)
    {
        $point = 0;
        $string = $string;

        $pattern = "/会员/";
        $reg = $this->reg($pattern, $string);
        if($reg ){
            $point1 = 100;
            $point += $point1;
        }

        $pattern = "/理事/";
        $reg = $this->reg($pattern, $string);
        if($reg ){
            $point2 = 200;
            $point += $point2;
        }

        $pattern = "/副会长/";
        $reg = $this->reg($pattern, $string);
        if($reg ){
            $point3 = 500;
            $point += $point3;
        }else{
            $pattern = "/会长/";
            $reg = $this->reg($pattern, $string);
            if($reg ){
                $point4 = 2000;
                $point += $point4;
            }
        }

        if($point > 2000){
            $point = 2000;
        }
        return $point;
    }


    //正则匹配
    function reg($pattern, $string)
    {
        // preg_match ( string $pattern , string $subject) 参数1：模式, 参数2：字符串
        if(preg_match($pattern, $string)){
            return 1;
        }else{
            return 0;
        }
    }




}


?>